/*
 * @Author: AiLjx
 * @Date: 2022-06-30 22:11:31
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-07-01 17:58:41
 */

// 按models目录约定注册 model，无需手动 app.model
import { Effect } from 'dva';
import { Reducer } from 'redux';

interface ICityObj {
  cityId: number;
  name: string;
  pinyin: string;
  isHot: number;
}

interface IState {
  cityName: string;
  cityId: string;
  list: Array<ICityObj>;
}

interface ICity {
  namespace: string;
  state: IState;
  effects: {
    getCityList: Effect;
  };
  reducers: {
    changeCity: Reducer;
    changeList: Reducer;
  };
}
export default <ICity>{
  // 命名空间，若不写则自动取文件名称
  namespace: 'city',
  state: {
    cityName: '北京',
    cityId: '110100',
    list: [],
  },

  reducers: {
    changeCity(prevState, action) {
      return {
        ...prevState,
        ...action.payload,
      };
    },

    changeList(prevState, action) {
      return {
        ...prevState,
        list: action.payload,
      };
    },
  },

  effects: {
    *getCityList(action, { call, put }) {
      // 发起请求
      const res = yield call(getList);
      // 发起新的reducer
      yield put({
        type: 'changeList',
        // 使用filterCity转换数据
        payload: filterCity(res),
      });
    },
  },
};

async function getList() {
  const res = await fetch('https://m.maizuo.com/gateway?k=5450705', {
    headers: {
      'X-Client-Info':
        '{"a":"3000","ch":"1002","v":"5.2.0","e":"1656580721116200340193281","bc":"110100"}',
      'X-Host': 'mall.film-ticket.city.list',
    },
  });
  const { data } = await res.json();
  // console.log('city请求的数据', data.cities);
  return data.cities;
}

interface InewlistItem {
  title: string;
  items: Array<ICityObj>;
}

// 处理请求返回的数据，使其符合antd-mobile IndexBar 序列组件的需求
const filterCity = (citys: Array<ICityObj>) => {
  // 存放26个因为字符
  const letterArr: Array<string> = [];
  const newlist: Array<InewlistItem> = [];

  // String.fromCharCode()根据ASCII码转换成英文字母，A是65
  for (let i = 65; i < 91; i++) {
    letterArr.push(String.fromCharCode(i));
  }

  letterArr.forEach((letter) => {
    const cityItems = citys.filter(
      (item) => item.pinyin.substring(0, 1).toUpperCase() === letter,
    );

    cityItems.length &&
      newlist.push({
        title: letter,
        items: cityItems,
      });
  });

  // console.log('city转换后的数据', newlist);
  return newlist;
};
